"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const path = tslib_1.__importStar(require("path"));
const utils_1 = require("../helper/utils");
exports.default = async (repoPath, options) => {
    const packageJsonPath = path.join(repoPath, './package.json');
    const exist = await utils_1.isExist(packageJsonPath);
    if (exist) {
        const pkg = require(packageJsonPath);
        const dependencies = pkg.dependencies;
        let needInstall = false;
        for (const key in dependencies) {
            const filepath = path.join(repoPath, `./node_modules/${key}/package.json`);
            if (await utils_1.isExist(filepath)) {
                const version = require(filepath).version;
                if (utils_1.compareVersion(dependencies[key].version, version)) {
                    needInstall = true;
                    break;
                }
            }
            else {
                needInstall = true;
                break;
            }
        }
        if (needInstall) {
            try {
                utils_1.send('正在安装依赖');
                const std = await utils_1.exec('npm i', { cwd: repoPath });
                utils_1.send(std.stderr);
                if (std.stdout) {
                    utils_1.send(std.stdout);
                    let cmd = '';
                    if (options.cmd) {
                        cmd = options.cmd;
                    }
                    else if (pkg.scripts && pkg.scripts.restart) {
                        cmd = pkg.scripts.restart;
                    }
                    if (cmd) {
                        const std = await utils_1.exec(cmd, { cwd: repoPath });
                        utils_1.send(std.stderr);
                        utils_1.send(std.stdout);
                    }
                }
            }
            catch (err) {
                utils_1.send(err, false);
            }
        }
        else {
            utils_1.send('没有依赖需要安装或更新');
        }
    }
    else if (options.cmd) {
        const std = await utils_1.exec(options.cmd, { cwd: repoPath });
        utils_1.send(std.stderr);
        utils_1.send(std.stdout);
    }
    utils_1.send('EXIT');
};
